<?php
if( !defined('IN_SEC') ){
	exit('Access Denied.');
}

class supcache{
	public function __construct(){
		$this->dir = APP_PATH . '/include/caches/';
		$this->suf = '.cache.php';
	}

	public function set($key, $val, $flag, $expire){
		$file = $this->name($key);
		$val = $this->var_code($val, $expire);
		$mkdir = is_dir(dirname($file)) ? '' : dirname($file);
		if ( $mkdir ){
			dmkdir($mkdir);
		}
		return file_put_contents($file, $val);
	}

	public function add($key, $val, $flag, $expire){
		if ( !$this->get($key) ){
			return $this->set($key, $val, $expire);
		}
		return null;
	}

	public function get($key){
		$cache = null;
		$file = $this->exists($key);
		if ( $file ){
			$data = include $file;
			if ( $data['expire'] && ((time() - $data['time']) > $data['expire']) || !$data['data']){
				unset($data);
				$this->del($key);
			}else{
				$cache = $data['encode'] ? json_decode($data['data'], true) : $data['data'];
			}
		}
		return $cache;
	}

	public function del($key = '', $exits = false){
		$file = $this->exists($key, $exits);
		if ( is_dir($file) ) {
			$subs = array_slice(scandir($file), 2);
			foreach ($subs as $k => $dir) {
				$path = $file . '/' . $dir;
				is_dir($path) ? $this->del($path, true) : unlink($path);
			}
			reset($subs);
			return rmdir($file);
		}else{
			if ( $file ){
				return unlink($file);
			}
		}
		return false;
	}

	public function exists($key, $exists = false){
		if( $exists ){
			return $key;
		}
		$file = $this->name($key);
		if ( !file_exists($file) && !$exists ){
			$file = false;
		}
		return $file;
	}

	private function name($key = ''){
		$md5 = md5($key);
		return $this->dir . substr($md5, 0, 2) . '/' . substr($md5, 3, 2) . '/' . substr($md5, 5, 2) . '/' . $md5 . $this->suf;

	}

	private function var_code($data, $expire){
		if ( is_array($data) ){
			$data = json_encode($data);
			$json = 1;
		}
		$data = array(
			'data' => $data,
			'expire' => $expire,
			'time' => time(),
			'encode' => $json,
		);
		$code = "<?php\n";
		$code .= "if ( !defined('IN_SEC') ){\n\texit();\n}\n\n";
		$data = var_export($data, true);
		$code .= "return {$data}";
		$code .= ";\n\n?>";
		return $code;
	}

	public function flush(){
		$data = false;
		if ( is_dir($this->dir) ){
			$data = array();
			$open = opendir($this->dir);

			while( $caches = readdir($open) ){
				if ( $caches != '.' && $caches != '..' ){
					$data[] = $this->del($this->dir . $caches . '/', true);
				}
			}
			closedir($open);
		}
		return $data;
	}
}

?>